package com.sky.controller.user;

import com.sky.constant.JwtClaimsConstant;
import com.sky.dto.UserLoginDto;
import com.sky.entity.User;
import com.sky.properties.JwtProperties;
import com.sky.result.Result;
import com.sky.service.IUserService;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 微信登录需求开发
 */
@RestController
@RequestMapping("/user/user")
@Slf4j
public class UserController {
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private IUserService userService;

    /**
     * 微信登录
     * @param userLoginDto :传入数据
     * @return :返回实体 dsxcf
     */
    @PostMapping("/login")
    public Result<UserLoginVo> login(@RequestBody UserLoginDto userLoginDto){
        log.info("{}",userLoginDto.getCode());
        //1 调用业务进行用户登录，返回用户对象
       User user= userService.wechatLogin(userLoginDto);
        //2 创建载荷，将用户id组件，写入载荷
        Map<String,Object> claims=new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID,user.getId());
        //3 生成 token令牌
        String jwt = JwtUtil.createJWT(jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims);
        //4  构建UserLoginVo
        UserLoginVo userLoginVo = UserLoginVo.builder()
                .id(user.getId())
                .openid(user.getOpenid())
                .token(jwt).build();
        //返回对象
        return Result.success(userLoginVo);
    }
    @PostMapping("/logout")
    public Result<String> logout(){
        return Result.success();
    }
}
